﻿package kliment.controls.deeplink {
	/**
	 * ...
	 * @author	Kliment
	 * @version	1.3.0
	 *
	 * class name: kliment.controls.deeplink.DeepLink
	 */
	public class DeepLink {
		private static const _DELIMER:String = '/';
		private var _listLinkPath:Array;

		public function DeepLink() {
			_init();

		}

		private function _init():void {
			_listLinkPath = new Array();
		}

		public function pars(pathNames:Array, parameter:Object = null):void {
			var newArray:Array = new Array();
			var length:uint = pathNames.length;
			var head:Boolean = true;
			for (var i:uint = 0; i < length; ++i ) {
				var old:DeepLinkItem = _listLinkPath[i];
				var newPart:String = pathNames[i];
				if (old && old.toString() == newPart && head) {
					newArray.push(old);
				} else {
					head = false;
					var link:DeepLinkItem = new DeepLinkItem(newPart, parameter);
					link.index = i;
					newArray.push(link);
				}
			}
			_listLinkPath = newArray;
		}

		public function getLink(lavel:uint):DeepLinkItem {
			return _listLinkPath[lavel];
		}

		public function getLastWithData():DeepLinkItem {
			var i:uint = _listLinkPath.length;
			var item:DeepLinkItem;
			while (i--) {
				item = _listLinkPath[i];
				if (item.data) {
					return item;
				}
			}
			return null;
		}

		public function getNextForLoad():DeepLinkItem {
			var length:uint = _listLinkPath.length;
			var item:DeepLinkItem;
			for (var i:uint = 0; i < length; ++i) {
				item = _listLinkPath[i];
				if (item.data && !item.isLoaded) {
					return item;
				}
			}
			return null;
		}

		public function push(value:DeepLinkItem):DeepLink {
			_listLinkPath.push(value);
			value.index = _listLinkPath.length - 1;
			return this;
		}

		public function leave(lavel:uint):DeepLink {
			_listLinkPath.splice(lavel, _listLinkPath.length - lavel);
			return this;
		}

		public function toString(limit:uint = 0):String {
			var result:String = '';
			if (limit <= 0)
				limit = _listLinkPath.length;
			for (var i:uint = 0; i < limit; ++i ) {
				result += _listLinkPath[i].toString();
			}
			return result;
		}

		public function get length():uint { return _listLinkPath.length; }
	}

}